# 5_1 使用使用I2S播放音乐：指定频率声音
# https://learn.adafruit.com/adafruit-esp32-s3-tft-feather/i2s

import time
import array
import math
import board
import audiocore
import audiobusio
import digitalio

'''
Board 3V to breakout VIN
Board GND to breakout GND
Board A0 to breakout BCLK
Board A1 to breakout LRC
Board A2 to breakout DIN
Board A3 to breakout GAIN
'''

I2S_BCLK = board.A0
I2S_LRC = board.A1
I2S_DIN = board.A2
I2S_GAIN = board.A3

print("init")

audio = audiobusio.I2SOut(I2S_BCLK, I2S_LRC, I2S_DIN)

gain = digitalio.DigitalInOut(I2S_GAIN)
gain.direction = digitalio.Direction.OUTPUT
gain.value = False

tone_volume = 0.1  # Increase this to increase the volume of the tone.
frequency = 440  # Set this to the Hz of the tone you want to generate.
length = 8000 // frequency
sine_wave = array.array("h", [0] * length)
for i in range(length):
    sine_wave[i] = int((math.sin(math.pi * 2 * i / length)) * tone_volume * (2 ** 15 - 1))
sine_wave_sample = audiocore.RawSample(sine_wave)

print(sine_wave[0:100])

while True:
    print("play tone")
    audio.play(sine_wave_sample, loop=True)
    time.sleep(1)
    print("stop")
    audio.stop()
    time.sleep(1)
